﻿ 
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.ComponentModel;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Xml.Serialization;
using System.Reflection;

namespace SysCommon.Log
{
    /// <summary>
    /// 类型转换
    /// </summary>
    public static class Types
    {

        //public static T GetCustomAttributes<T>(this Assembly ass) where T : class
        //{
        //    var attributeTree =
        //     (from t in ass.GetExportedTypes()
        //      where t.IsClass && t.IsPublic && typeof(Attribute).IsAssignableFrom(t)
        //      let typeHierarchy = t.Name
        //      select typeHierarchy).ToArray();

        //}

        /// <summary>
        /// 类型转换方法 
        /// </summary>
        /// <param name="val"></param>
        /// <param name="tp"></param>
        /// <returns></returns>
        public static object ConvertType(object val, Type tp)
        {
            if (tp == null) throw new Exception("要转换的类型错误");
            if (val == null) return null;//类型的默认值
            //泛型Nullable判断，取其中的类型
            if (tp.IsGenericType)
            {
                tp = tp.GetGenericArguments()[0];
            }
            //string直接返回转换
            if (tp.Name.ToLower() == "string")
            {
                return val.ToString();
            }
            //反射获取TryParse方法
            var TryParse = tp.GetMethod("TryParse", BindingFlags.Public | BindingFlags.Static, Type.DefaultBinder,
                                            new Type[] { typeof(string), tp.MakeByRefType() },
                                            new ParameterModifier[] { new ParameterModifier(2) });
            var parameters = new object[] { val, Activator.CreateInstance(tp) };
            bool success = (bool)TryParse.Invoke(null, parameters);
            //成功返回转换后的值，否则返回类型的默认值
            if (success)
            {
                return parameters[1];
            }
            return tp.Assembly.CreateInstance(tp.FullName, false);
        }
        /// <summary>
        /// 将数据库中的值转化为字符值
        /// </summary>
        /// <param name="rowvalue"></param>
        /// <returns></returns>
        public static string DBVToString(this object rowvalue)
        {
            if (rowvalue != null && rowvalue != DBNull.Value)
            {
                return rowvalue.ToString();
            }
            else
            {
                return "";
            }
        }
        /// <summary>
        /// 将数据库中的值转化为字符值
        /// </summary>
        /// <param name="rowvalue"></param>
        /// <returns></returns>
        public static T DBValueToObj<T>(this object rowvalue)
        {
            if (rowvalue != null && rowvalue != DBNull.Value)
            {
                if (rowvalue is T)
                {
                    return (T)rowvalue;
                }
                else
                {
                    object v = default(T);
                    try
                    {
                        v = Convert.ChangeType(rowvalue, typeof(T));
                    }
                    catch (Exception msg)
                    {
                    }
                    return (T)v;
                }
            }
            else
            {
                return default(T);
            }
        }
        /// <summary>
        /// 转化为目标对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ConvertTo<T>(this object value) { return value.ConvertTo(default(T)); }
        /// <summary>
        /// 转化为目标对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T ConvertTo<T>(this object value, T defaultValue)
        {
            if (value != null)
            {
                var targetType = typeof(T);
                var converter = TypeDescriptor.GetConverter(value);
                if (converter != null)
                {
                    if (converter.CanConvertTo(targetType)) return (T)converter.ConvertTo(value, targetType);
                }
                converter = TypeDescriptor.GetConverter(targetType);
                if (converter != null)
                {
                    try { if (converter.CanConvertFrom(value.GetType())) return (T)converter.ConvertFrom(value); }
                    catch { }
                }
            }
            return defaultValue;
        }
        /// <summary>
        /// 转化为目标对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="defaultValue">默认值</param>
        /// <param name="ignoreException">如果发生错误是否采用默认值</param>
        /// <returns></returns>
        public static T ConvertTo<T>(this object value, T defaultValue, bool ignoreException)
        {
            if (ignoreException)
            {
                try
                {
                    return value.ConvertTo<T>();
                }
                catch
                {
                    return defaultValue;
                }
            }
            return value.ConvertTo<T>();
        }
        /// <summary>
        /// 转化为Int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static int ToInt(this object strValue, int defValue)
        {
            int def = 0;
            int.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为Int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static byte ToTinyInt(this object strValue, byte defValue)
        {
            byte def = 0; byte.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为short型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static short ToSmallInt(this object strValue, short defValue)
        {
            short def = 0; short.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为decimal型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static decimal ToDecimal(this object strValue, decimal defValue)
        {
            decimal def = 0;
            decimal.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        ///// <summary>
        ///// 转化为float型
        ///// </summary>
        ///// <param name="strValue"></param>
        ///// <param name="defValue">默认值</param>
        ///// <returns></returns>
        //public static float ToFloat(this object strValue, float defValue)
        //{
        //    float def = 0;
        //    float.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        //}
        /// <summary>
        /// 转化为Int64型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static Int64 ToBigInt(this object strValue, Int64 defValue)
        {
            Int64 def = 0;
            Int64.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为decimal型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static decimal ToMoney(this object strValue, decimal defValue)
        {
            decimal def = 0;
            decimal.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static int ToInteger(this object strValue, int defValue)
        {
            int def = 0;
            int.TryParse(strValue.ToString(), out def); return def == 0 ? defValue : def;
        }
        /// <summary>
        /// 转化为bool型
        /// </summary>
        /// <param name="ExPRession"></param>
        /// <param name="defValue">默认值</param>
        /// <returns></returns>
        public static bool ToBool(this object ExPRession, bool defValue)
        {
            if (ExPRession != null)
            {
                if (string.Compare(ExPRession.ToString(), "true", true) == 0) return true;
                if (string.Compare(ExPRession.ToString(), "false", true) == 0) return false;
                if (string.Compare(ExPRession.ToString(), "1", true) == 0) return true;
                if (string.Compare(ExPRession.ToString(), "0", true) == 0) return false;
            }
            return defValue;
        }
        /// <summary>
        /// /将二进制数组从指定的位置截取指定的长度的子串形成新的二进制数组
        /// </summary>
        /// <param name="bytesValue">源二进制数组</param>
        /// <param name="startIndex">指定的位置（要截取的开始位置）</param>
        /// <param name="length">要截取的长度</param>
        /// <returns>返回截取成功的子串，如果指定的位置或长度超出源数组的范围则返回Null</returns>
        public static byte[] SubBytes(this byte[] bytesValue, int startIndex, int length)
        {
            int b = bytesValue.Length;
            if ((startIndex == 0) && length == b) return bytesValue;
            if (startIndex < b && (startIndex + length) <= b)
            {
                byte[] ar = new byte[length];
                Buffer.BlockCopy(bytesValue, startIndex, ar, 0, length);
                //Array.Copy(bytesValue, startIndex, ar, 0, length);
                return ar;
            }
            return null;
        }

        /// <summary>
        /// 将Int16转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this Int16 intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        ///// <summary>
        ///// 将int转变为二进制数
        ///// </summary>
        ///// <param name="intValue"></param>
        ///// <returns></returns>
        //public static byte[] GetBytes(this Enum intValue)
        //{
        //    int  e =(int)intValue;
        //   return BitConverter.GetBytes(e);
        //}
        /// <summary>
        /// 将int转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this int intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将long转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this long intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将decimal转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this decimal intValue)
        {
            List<byte> bl = new List<byte>();
            int[] b = decimal.GetBits(intValue);
            bl.AddRange(BitConverter.GetBytes(b[0]));
            bl.AddRange(BitConverter.GetBytes(b[1]));
            bl.AddRange(BitConverter.GetBytes(b[2]));
            bl.AddRange(BitConverter.GetBytes(b[3]));
            return bl.ToArray();
        }
        /// <summary>
        /// 将bool转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this bool intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将char转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this char intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将double转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this double intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将float转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this float intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        ///// <summary>
        ///// 将uint转变为二进制数
        ///// </summary>
        ///// <param name="intValue"></param>
        ///// <returns></returns>
        //public static byte[] GetBytes(this uint intValue)
        //{
        //    return BitConverter.GetBytes(intValue);
        //}
        /// <summary>
        /// 将uint32转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this UInt32 intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将ulong转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this ulong intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将ushort转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this ushort intValue)
        {
            return BitConverter.GetBytes(intValue);
        }
        /// <summary>
        /// 将string转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetTLVbytes(this string intValue, int len)
        {
            List<byte> bt = new List<byte>();
            bt.Add(0x02);
            if (intValue.Length > len)
            {
                byte[] bl = Encoding.UTF8.GetBytes(intValue.Substring(0, len));
                bt.AddRange(((UInt16)bl.Length).GetBytes());
                bt.AddRange(bl);
            }
            else
            {
                byte[] bl = Encoding.UTF8.GetBytes(intValue.PadLeft(len));
                bt.AddRange(((UInt16)bl.Length).GetBytes());
                bt.AddRange(bl);
            }
            return bt.ToArray();
        }
        /// <summary>
        /// 将bytes转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetTLVbytes(this byte[] intValue)
        {
            List<byte> bt = new List<byte>();
            bt.Add(0x04);
            int c = Int32.MaxValue / 2;
            if (intValue.Length > c)
            {
                byte[] bl = intValue.SubBytes(0, c);
                bt.AddRange((bl.Length).GetBytes());
                bt.AddRange(bl);
            }
            else
            {
                bt.AddRange((intValue.Length).GetBytes());
                bt.AddRange(intValue);
            }
            return bt.ToArray();
        }
        /// <summary>
        /// 将string转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetTLVbytes(this string intValue)
        {
            List<byte> bt = new List<byte>();
            bt.Add(0x02);
            int c = UInt16.MaxValue / 2;
            if (intValue.Length > c)
            {
                byte[] bl = Encoding.UTF8.GetBytes(intValue.Substring(0, c));
                bt.AddRange(((UInt16)bl.Length).GetBytes());
                bt.AddRange(bl);
            }
            else
            {
                byte[] bl = Encoding.UTF8.GetBytes(intValue);
                bt.AddRange(((UInt16)bl.Length).GetBytes());
                bt.AddRange(bl);
            }
            return bt.ToArray();
        }
        /// <summary>
        /// 将string转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <returns></returns>
        public static byte[] GetBytes(this string intValue)
        {
            return Encoding.UTF8.GetBytes(intValue);
        }

        /// <summary>
        /// 将指定string长度的字符串转变为二进制数
        /// </summary>
        /// <param name="intValue"></param>
        /// <param name="len">定长数据,没有指定长度用空格字符代替</param>
        /// <returns></returns>
        public static byte[] GetBytes(this string intValue, int len)
        {
            byte[] k = Encoding.UTF8.GetBytes(intValue);
            if (k.Length > len)
            {
                return k.SubBytes(0, len);
            }
            else
            {
                List<byte> u = new List<byte>();
                u.AddRange(k);
                for (int i = u.Count; i < len; i++)
                {
                    u.Add(0x20);
                }
                return u.ToArray();
            }
        }
        /// <summary>
        /// 将二进制数转变为bool
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static bool ToBoolean(this byte[] value, int startIndex)
        {
            return BitConverter.ToBoolean(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为bool
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static bool ToBoolean(this byte value, int startIndex)
        {
            if (value == 0x01)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        /// <summary>
        /// 将二进制数转变为char
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static char ToChar(this byte value, int startIndex)
        {
            byte[] valuec = new byte[] { value };
            return BitConverter.ToChar(valuec, 0);
        }
        /// <summary>
        /// 将二进制数转变为char
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static char ToChar(this byte[] value, int startIndex)
        {
            return BitConverter.ToChar(value, startIndex);
        }
        /// <summary>
        /// 转化为Double型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static Double ToDouble(this byte[] value)
        {
            return BitConverter.ToDouble(value, 0);
        }
        /// <summary>
        /// 将二进制数转变为Double
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static double ToDouble(this byte[] value, int startIndex)
        {
            return BitConverter.ToDouble(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToInt16
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static short ToInt16(this byte[] value, int startIndex)
        {
            return BitConverter.ToInt16(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToInt16
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static short ToInt16(this byte[] value)
        {
            return BitConverter.ToInt16(value, 0);
        }
        /// <summary>
        /// 将二进制数转变为ToUInt16
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static UInt16 ToUInt16(this byte[] value, int startIndex)
        {
            return BitConverter.ToUInt16(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToUInt16
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static UInt16 ToUInt16(this byte[] value)
        {
            return BitConverter.ToUInt16(value, 0);
        }

        /// <summary>
        /// /将二进制数转变为ToInt32
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToInt(this byte[] value)
        {
            return BitConverter.ToInt32(value, 0);
        }
        /// <summary>
        /// /将二进制数转变为ToInt32
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static int ToInt32(this byte[] value)
        {
            return BitConverter.ToInt32(value, 0);
        }
        /// <summary>
        /// /将二进制数转变为ToInt32
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static int ToInt32(this byte[] value, int startIndex)
        {
            return BitConverter.ToInt32(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToInt64
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static long ToLong(this byte[] value)
        {
            return BitConverter.ToInt64(value, 0);
        }
        /// <summary>
        /// 将二进制数转变为ToInt64
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static long ToLong(this byte[] value, int startIndex)
        {
            return BitConverter.ToInt64(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToSingle
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static float ToSingle(this byte[] value)
        {
            return BitConverter.ToSingle(value, 0);
        }
        /// <summary>
        /// 将二进制数转变为ToSingle
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static float ToSingle(this byte[] value, int startIndex)
        {
            return BitConverter.ToSingle(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为decimal
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this byte[] value)
        {
            if (value.Length < 16) throw new Exception("转化为decimal至少要16个字节");
            int[] b = new int[] { 0, 0, 0, 0 };
            b[0] = value.ToInt32(0);
            b[1] = value.ToInt32(4);
            b[2] = value.ToInt32(8);
            b[3] = value.ToInt32(12);
            return new decimal(b);
        }
        /// <summary>
        /// 将二进制数转变为BitTrimX00
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string BitRightTrimX00(this byte[] value)
        {
            List<byte> l = new List<byte>();
            int i0 = -1;
            for (int i = 0; i < value.Length; i++)
            {
                if (value[i] != 0x00)
                {
                    i0 = i;
                }
                if (i0 > -1)
                {
                    l.Add(value[i]);
                }
            }
            for (int i = l.Count - 1; i > -1; i--)
            {
                if (value[i] != 0x00)
                {
                    break;
                }
                l.Remove(value[i]);
            }
            return Encoding.UTF8.GetString(l.ToArray());
        }

        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] TLVBitToBytes(this byte[] value, int iStateAt, ref int bitLen)
        {
            byte[] PL2 = value.SubBytes(iStateAt, 1);
            if (0x04 == PL2[0])//如果是二进制类型
            {
                byte[] PL21 = value.SubBytes(iStateAt + 1, 4);
                if (PL21 != null)
                {
                    int Len = PL21.ToInt();
                    bitLen = Len + 5;
                    return value.SubBytes(iStateAt + 5, Len);
                }
            }
            return null;
        }
        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value">要解释的二进制数据</param>
        /// <param name="iStateAt">数据开始位置</param>
        /// <param name="bitLen">数据长度</param>
        /// <returns></returns>
        public static string TLVBitToString(this byte[] value, int iStateAt, ref int bitLen)
        {
            string str = "";
            byte[] PL2 = value.SubBytes(iStateAt, 1);
            if (0x02 == PL2[0])//如果是字符串类型
            {
                byte[] PL21 = value.SubBytes(iStateAt + 1, 2);
                if (PL21 != null)
                {
                    UInt16 Len = PL21.ToUInt16();
                    bitLen = Len + 3;
                    byte[] PL3 = value.SubBytes(iStateAt + 3, Len);
                    if (PL3 != null)
                    {
                        str = PL3.BitToString();
                    }
                    else
                    {
                        str = null;
                    }
                }
                else
                {
                    str = null;
                }
            }
            else
            {
                return null;
            }
            return str;
        }
        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string BitToString(this byte[] value, int iStateAt, int bitLen)
        {
            if (value.Length > iStateAt + bitLen)
            {
                byte[] PL1 = value.SubBytes(iStateAt, bitLen);
                return PL1.BitToString();
            }
            return "";
        }
        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static string BitToString(this byte[] value)
        {
            return Encoding.UTF8.GetString(value);
        }
        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static string ToString(this  byte[] value, int startIndex)
        {
            byte[] k = value.SubBytes(startIndex, value.Length - startIndex);
            return Encoding.UTF8.GetString(k);
        }
        /// <summary>
        /// 将二进制数转变为ToString
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <param name="length"></param>
        /// <returns></returns>
        public static string ToString(this byte[] value, int startIndex, int length)
        {
            byte[] k = value.SubBytes(startIndex, length);
            return Encoding.UTF8.GetString(k);
        }

        /// <summary>
        /// 将二进制数转变为ToUInt32
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static uint ToUInt32(this byte[] value)
        {
            return BitConverter.ToUInt32(value, 0);
        }
        /// <summary>
        /// 将二进制数转变为ToUInt32
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static uint ToUInt32(this byte[] value, int startIndex)
        {
            return BitConverter.ToUInt32(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToUInt64
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static ulong ToUInt64(this byte[] value, int startIndex)
        {
            return BitConverter.ToUInt64(value, startIndex);
        }
        /// <summary>
        /// 将二进制数转变为ToUInt64
        /// </summary>
        /// <param name="value"></param>
        /// <param name="startIndex"></param>
        /// <returns></returns>
        public static Int64 ToInt64(this byte[] value, int startIndex)
        {
            return (Int64)BitConverter.ToInt64(value, startIndex);
        }
        /// <summary>
        /// 转化为float型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static float ToFloat(this byte[] value)
        {
            return BitConverter.ToSingle(value, 0);
        }
        /// <summary>
        /// 转化为float型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static float ToFloat(this byte[] value, int startIndex)
        {
            return BitConverter.ToSingle(value, startIndex);
        }
        /// <summary>
        /// 转化为bool型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static bool ToBool(this byte[] value) { return ToBool(value, 0); }

        /// <summary>
        /// 转化为bool型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static bool ToBool(this byte[] value, int startIndex) { return BitConverter.ToBoolean(value, startIndex); }
        /// <summary>
        /// 转化为int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static int ToInt(this object strValue) { return strValue.ToInt(0); }
        /// <summary>
        /// 转化为int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static byte ToTinyInt(this object strValue) { return strValue.ToTinyInt(0); }
        /// <summary>
        /// 转化为short型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static short ToSmallInt(this object strValue) { return strValue.ToSmallInt(0); }
        /// <summary>
        /// 转化为decimal型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static decimal ToDecimal(this object strValue) { return strValue.ToDecimal(0); }
        ///// <summary>
        ///// 转化为float型
        ///// </summary>
        ///// <param name="strValue"></param>
        ///// <returns></returns>
        //public static float ToFloat(this object strValue) { return strValue.ToFloat(0); }
        /// <summary>
        /// 转化为Int64型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static Int64 ToBigInt(this object strValue) { return strValue.ToBigInt(0); }
        /// <summary>
        /// 转化为decimal型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static decimal ToMoney(this object strValue) { return strValue.ToMoney(0); }
        /// <summary>
        /// 转化为int型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static int ToInteger(this object strValue) { return strValue.ToInteger(0); }
        /// <summary>
        /// 转化为bool型
        /// </summary>
        /// <param name="strValue"></param>
        /// <returns></returns>
        public static bool ToBool(this object strValue) { return strValue.ToBool(false); }

        /// <summary>
        /// 获取枚举值的特性名称对象集
        /// </summary>
        /// <typeparam name="T">枚举特性类型</typeparam>
        /// <param name="eValue">枚举值</param>
        /// <returns>返回一个特性实体</returns>
        public static T GetAttributeFirst<T>(this Enum eValue) where T : Attribute
        {
            FieldInfo EnumInfo = eValue.GetType().GetField(eValue.ToString());
            if (null == EnumInfo)
            {
                return null;
            }
            var attributes = EnumInfo.GetCustomAttributes(typeof(T), false);
            if ((attributes != null) && (attributes.Length > 0))
            {
                return (attributes[0] as T);
            }
            return null;
        }
        /// <summary>
        /// /将int值转化为枚举型值
        /// </summary>
        /// <param name="iValue">int型值</param>
        /// <returns>返回枚举型值</returns>
        //generic <typename T> where T: value class, Enum
        public static T ToEnum<T>(this int iValue) where T : struct, IComparable, IFormattable, IConvertible //where T : System.Enum
        {
            return (T)Enum.ToObject(typeof(T), iValue);
        }
        /// <summary>
        /// /将uint值转化为枚举型值
        /// </summary>
        /// <param name="iValue">int型值</param>
        /// <returns>返回枚举型值</returns>
        public static T ToEnum<T>(this uint iValue) where T : struct, IComparable, IFormattable, IConvertible
        {
            return (T)Enum.ToObject(typeof(T), iValue);
        }
        /// <summary>
        /// 调用一个成员方法
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="methodName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static object InvokeMethod(this object obj, string methodName, params object[] parameters)
        {
            return InvokeMethod<object>(obj, methodName, parameters);
        }
        /// <summary>
        /// 调用一个成员方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="methodName"></param>
        /// <returns></returns>
        public static T InvokeMethod<T>(this object obj, string methodName)
        {
            return InvokeMethod<T>(obj, methodName, null);
        }
        /// <summary>
        /// 调用一个成员方法
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="methodName"></param>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static T InvokeMethod<T>(this object obj, string methodName, params object[] parameters)
        {
            var type = obj.GetType();
            var method = type.GetMethod(methodName);
            if (method == null) throw new ArgumentException(string.Format("Method '{0}' not found.", methodName), methodName);
            var value = method.Invoke(obj, parameters);
            return (value is T ? (T)value : default(T));
        }
        /// <summary>
        /// 获取属性名称对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static object GetPropertyValue(this object obj, string propertyName)
        {
            return GetPropertyValue<object>(obj, propertyName, null);
        }
        /// <summary>
        /// 获取属性名称对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static T GetPropertyValue<T>(this object obj, string propertyName)
        {
            return GetPropertyValue<T>(obj, propertyName, default(T));
        }
        /// <summary>
        /// 获取属性名称对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <returns></returns>
        public static string[] GetPropertyName<T>(this T obj)
        {
            List<string> s = new List<string>();
            var readableProps =
                from prop in typeof(T).GetProperties(
                    BindingFlags.Public | BindingFlags.Instance)
                where prop.CanRead && prop.CanWrite
                select prop;
            foreach (PropertyInfo k in readableProps)
            {
                s.Add(k.Name);
            }
            return s.ToArray();
        }

        /// <summary>
        /// 获取属性名称对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <param name="defaultValue"></param>
        /// <returns></returns>
        public static T GetPropertyValue<T>(this object obj, string propertyName, T defaultValue)
        {
            var type = obj.GetType();
            var property = type.GetProperty(propertyName);
            if (property == null) throw new ArgumentException(string.Format("Property '{0}' not found.", propertyName), propertyName);
            var value = property.GetValue(obj, null);
            return (value is T ? (T)value : defaultValue);
        }
        /// <summary>
        /// 设置属性名称对象值
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="propertyName"></param>
        /// <param name="value"></param>
        public static void SetPropertyValue(this object obj, string propertyName, object value)
        {
            var type = obj.GetType();
            var property = type.GetProperty(propertyName);
            if (property == null) throw new ArgumentException(string.Format("Property '{0}' not found.", propertyName), propertyName);
            if (property.PropertyType.FullName != value.GetType().FullName)
            {
                try
                {
                    object c = Convert.ChangeType(value, property.PropertyType);
                    if (property.CanWrite)
                    {
                        property.SetValue(obj, c, null);
                    }
                }
                catch
                {
                }
            }
            else
            {
                property.SetValue(obj, value, null);
            }
        }


        /// <summary>
        /// 获取特性名称对象集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetAttributes<T>(this object obj) where T : Attribute
        {
            return GetAttributes<T>(obj);
        }
        /// <summary>
        /// 获取特性名称对象集
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <param name="includeInherited"></param>
        /// <returns></returns>
        public static IEnumerable<T> GetAttributes<T>(this object obj, bool includeInherited) where T : Attribute
        {
            var type = (obj as Type ?? obj.GetType());
            foreach (var attribute in type.GetCustomAttributes(typeof(T), includeInherited))
            {
                if (attribute is T) yield return (T)attribute;
            }
        }
        /// <summary>
        /// 获取枚举值的特性名称对象集
        /// </summary>
        /// <typeparam name="T">枚举特性类型</typeparam>
        /// <param name="eValue">枚举值</param>
        /// <returns>返回一个特性实体</returns>
        public static T GetAttributeFirst<T>(this object eValue) where T : Attribute
        {
            FieldInfo EnumInfo = eValue.GetType().GetField(eValue.ToString());
            if (null == EnumInfo)
            {
                return null;
            }
            var attributes = EnumInfo.GetCustomAttributes(typeof(T), false);
            if ((attributes != null) && (attributes.Length > 0))
            {
                return (attributes[0] as T);
            }
            return null;
        }

        /// <summary>
        /// 获取一个对象指定属性名称的字段特性（FieldAttribute）的注释
        /// </summary>
        /// <typeparam name="T">具有字段特性的实体类型</typeparam>
        /// <param name="propertyName">指定实体中的属性名称</param>
        /// <returns>返回特性注释文本</returns>
        public static D GetCustomAttributeFirstEnitiy<T, D>(this T evalue, string propertyName) where D : Attribute
        {
            PropertyInfo filist = evalue.GetType().GetProperty(propertyName);
            if (filist == null)
            {
                return null;
            }
            var attributes = filist.GetCustomAttributes(typeof(D), false);
            if ((attributes != null) && (attributes.Length > 0))
            {
                return attributes[0] as D;
            }
            return null;
        }

        /// <summary>
        /// 是否是这个类型
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsType(this object obj, Type type)
        {
            return obj.GetType().Equals(type);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T Type2T<T>(this object value) { return (T)value; }
        /// <summary>
        /// 是否是数组
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsArray(this object obj)
        {
            return obj.IsType(typeof(System.Array));
        }
        /// <summary>
        /// 是否是数据库空值
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        public static bool IsDBNull(this object obj)
        {
            return obj.IsType(typeof(DBNull));
        }
        /// <summary>
        /// 序列化对象成二进制流
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static byte[] Serialize(this object value)
        {
            MemoryStream ms = new MemoryStream();
            BinaryFormatter bf1 = new BinaryFormatter();
            bf1.Serialize(ms, value);
            return ms.ToArray();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="this"></param>
        /// <param name="parameterName"></param>
        public static void CheckOnNull(this object @this, string parameterName)
        {
            if (@this.IsNull()) throw new ArgumentNullException(parameterName);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="this"></param>
        /// <param name="parameterName"></param>
        /// <param name="message"></param>
        public static void CheckOnNull(this object @this, string parameterName, string message)
        {
            if (@this.IsNull()) throw new ArgumentNullException(parameterName, message);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static bool IsNull(this object @this)
        {
            return @this == null;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="this"></param>
        /// <returns></returns>
        public static bool IsNotNull(this object @this)
        {
            return !@this.IsNull();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T UnsafeCast<T>(this object value)
        {
            return value.IsNull() ? default(T) : (T)value;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T SafeCast<T>(this object value)
        {
            return value is T ? value.UnsafeCast<T>() : default(T);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static bool InstanceOf<T>(this object value)
        {
            return value is T;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <param name="fileName"></param>
        public static void SerializeXmlFile(this object o, string fileName)
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            if (!File.Exists(fileName)) return;
            using (FileStream stream = new FileStream(fileName, FileMode.Create, FileAccess.Write)) serializer.Serialize(stream, o);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static T DeserializeXmlFile<T>(string fileName)
        {
            T o;
            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (FileStream stream = new FileStream(fileName, FileMode.Open, FileAccess.Read)) o = (T)serializer.Deserialize(stream);
            return o;
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="o"></param>
        /// <returns></returns>
        public static string SerializeXml(this object o)
        {
            XmlSerializer serializer = new XmlSerializer(o.GetType());
            StringBuilder stringBuilder = new StringBuilder();
            using (TextWriter textWriter = new StringWriter(stringBuilder)) serializer.Serialize(textWriter, o);
            return stringBuilder.ToString();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="xml"></param>
        /// <returns></returns>
        public static T DeserializeXml<T>(this string xml)
        {
            return (T)Deserialize(xml, typeof(T));
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static object Deserialize(string xml, Type type)
        {
            object o;
            XmlSerializer serializer = new XmlSerializer(type);
            using (TextReader textReader = new StringReader(xml)) o = serializer.Deserialize(textReader);
            return o;
        }
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="o"></param>
        //public static void Write(this object o) { Msg.Write(o); }
        ///// <summary>
        ///// 
        ///// </summary>
        ///// <param name="o"></param>
        //public static void WriteEnd(this object o) { Msg.WriteEnd(o); }

        /// <summary>
        /// 转换为指定类型的对象
        /// </summary>
        /// <typeparam name="T">返回对象的类型</typeparam>
        /// <param name="value">类型</param>
        /// <returns>返回该类型对象</returns>
        public static T ToType<T>(this object value)
        {
            try
            {
                return (T)Convert.ChangeType(value, typeof(T));
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 返回数据库类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static SqlDbType ToSqlDbType(this Type type)
        {
            try
            {
                Dictionary<string, string> comparisons = new Dictionary<string, string>()
                {
                    {"System.Int64", "BigInt"},
                    {"System.Byte[]", "Binary"},
                    {"System.Boolean", "Bit"},
                    {"System.String", "NVarChar"},
                    {"System.Char[]", "NVarChar"},
                    {"System.DateTime", "DateTime"},
                    {"System.Decimal", "Decimal"},
                    {"System.Double", "Float"},
                    {"System.Int32", "Int"},
                    {"System.Single", "Real"},
                    {"System.Int16", "SmallInt"},
                    {"System.Object", "Variant"},
                    {"System.Byte", "TinyInt"},
                    {"System.Guid", "UniqueIdentifier"}
                };

                return (SqlDbType)Enum.Parse(typeof(SqlDbType), comparisons[type.FullName.TrimEnd("&".ToCharArray())]);
            }
            catch
            {
                throw;
            }
        }
        /// <summary>
        /// 由数据库类型转变指定的类型
        /// </summary>
        /// <param name="type">数据库类型</param>
        /// <returns>返回指定类型</returns>
        public static Type ToType(this SqlDbType type)
        {
            try
            {
                Dictionary<string, string> comparisons = new Dictionary<string, string>()
                {
                    {"BigInt","System.Int64"},
                    {"Binary","System.Byte[]"},
                    {"Bit","System.Boolean"},
                    {"Char","System.String"},
                    {"DateTime","System.DateTime"},
                    {"Date","System.DateTime"},
                    {"Decimal","System.Decimal"},
                    {"Float","System.Double"},
                    {"Image","System.Byte[]"},
                    {"Int","System.Int32"},
                    {"Money","System.Decimal"},
                    {"NChar","System.String"},
                    {"NText","System.String"},
                    {"Numeric", "System.Decimal"},
                    {"NVarChar","System.String"},
                    {"Real","System.Single"},
                    {"SmallDateTime","System.DateTime"},
                    {"SmallInt","System.Int16"},
                    {"SmallMoney","System.Decimal"},
                    {"Variant","System.Object"},
                    {"Text","System.String"},
                    {"Timestamp","System.Byte[]"},
                    {"TinyInt","System.Byte"},
                    {"UniqueIdentifier","System.Guid"},
                    {"VarBinary","System.Byte[]"},
                    {"VarChar","System.String"}
                };

                return Type.GetType(comparisons[type.ToString()]);
            }
            catch
            {
                throw;
            }
        }

        /// <summary>
        /// 获取一个对象的各个属性中存在字段特性（FieldAttribute）的总数
        /// </summary>
        /// <typeparam name="T">具有字段特性的实体类型</typeparam>
        /// <returns>返回特性的总数</returns>
        public static int GetFieldAttributeCount<T>(this T evalue)
        {
            PropertyInfo[] filist = evalue.GetType().GetProperties();
            var readableProps =
               from prop in filist
               where (prop.GetCustomAttributes(typeof(FieldAttribute), false).Where(c => c != null).Count() > 0)
               select prop;
            if ((readableProps != null) && (readableProps.Count() > 0))
            {
                return readableProps.Count();
            }
            return 0;
        }





        //public static string ToJson(this object obj)
        //{
        //    return ToJson(obj, null);
        //}
        //public static string ToJson(this object obj, IEnumerable<javaScriptConverter> jsonConverters)
        //{
        //    JavascriptSerializer serializer = new JavaScriptSerializer();
        //    if (jsonConverters != null) serializer.RegisterConverters(jsonConverters ?? new JavaScriptConverter[0]);
        //    return serializer.Serialize(obj);
        //}
    }
}
